package com.tanhua.server.controller;

import com.tanhua.autoconfig.templates.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UsersService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.POST;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: tanhua
 * @description:
 * @author: MR.peng
 * @create: 2022-03-08 20:52
 **/

@RestController
@RequestMapping("/users")
public class UsersController {


    @Autowired
    private UsersService usersService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /*
    *
    * 根据Id查询用户信息
    * Path： /users
      Method： GET
      * 请求参数：
      *     Query:userID (可能为null)
      * 请求头参数：Authorization(当前操作的用户id)
      * 响应数据:
      *     UserInfo
      * 参数解析：
      *     userID:查询其他用户的id
      *     当userID != null 表示查询其他用户资料
      *     当userID == null 表示查询当前用户(解析Authorization)
    * */

    @GetMapping
    public UserInfoVo users(Long userID){
        Long userId = userID;
        if(userID == null){//查询当前用户
//            //1.获取参数
//            //1.判断token
//            boolean verifyToken = JwtUtils.verifyToken(token);
//            if (!verifyToken){
//                throw  new  RuntimeException("用户未登录");
//            }
//            //2.解析token(用户id)
//            Claims claims = JwtUtils.getClaims(token);
//            userId = claims.get("id", Long.class);
            userId = UserHolder.getUserId();
        }
        //调用service查询
        UserInfoVo userInfo = usersService.findUserINfoById(userId);
        return  userInfo;
    }

    /*
        更新用户信息
        请求头参数：Authorization(当前操作的用户id)
        返回值：void
     */
    @PutMapping
    public ResponseEntity updateUserInfo(@RequestBody UserInfo info){
        //1.获取参数
        //1.获取参数
        //1.1.判断token
//        boolean verifyToken = JwtUtils.verifyToken(token);
//        if (!verifyToken){
//            throw  new  RuntimeException("用户未登录");
//        }
//        //1.2.解析token(用户id)
//        Claims claims = JwtUtils.getClaims(token);
//        Long userId = claims.get("id", Long.class);
        Long userId = UserHolder.getUserId();
        //1.3.设置到info对象
        info.setId(userId);
        //2.调用service
        usersService.updateUserInfo(info);
        return ResponseEntity.ok(null);
    }


    /*
    * 查询通用设置
    * 接口路径：GET   /users/settings
    * 返回值：SettingsVo
    * */
    @GetMapping("/settings")
    public ResponseEntity settings(){
        //1.获取参数（无）
        //2.调用service，获取SettingsVo
        SettingsVo vo  =   usersService.settings();
        //3.构造返回值
        return ResponseEntity.ok(vo);

    }


    /*
    * 设置陌生人问题
    * 接口路径:POST /questions
    * 参数Body:content
    * {
    *      "content":"问题"
    * }
    * 返回值：void
    *
    * */
    @PostMapping("/questions")
    public ResponseEntity questions(@RequestBody Map map){
        //1.获取参数
        String content = map.get("content").toString();
        //2.调用service
        usersService.questions(content);
        //3.返回
        return ResponseEntity.ok(null);

    }

    /*
    * 设置通知开关
    *设置接口路径：POST /notifications/setting
    * 参数Body
    *   likeNotification,pinglunNotification,gonggaoNotification
    * 返回值:void
    *
    *
    * */
    @PostMapping("/notifications/setting")
    public ResponseEntity setting(@RequestBody Map map){
        //1.获取参数
        Boolean like = (Boolean) map.get("likeNotification");
        Boolean pinglun = (Boolean) map.get("pinglunNotification");
        Boolean gonggao = (Boolean) map.get("gonggaoNotification");
        //2.调用service
        usersService.setting(like,pinglun,gonggao);

        //3.返回
        return ResponseEntity.ok(null);
    }


    /*

    分页查询黑名单数据
    * 接口路径：GET  /blacklist
    请求参数： Query
          page,pageSize
          返回值：PageResult
    *
    * */
    @GetMapping("/blacklist")
    public ResponseEntity blacklist(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer pageSize){
        //1.调用service
        PageResult vo = usersService.blacklist(page,pageSize);
        //2.构造返回
        return ResponseEntity.ok(vo);
    }

    /*
    *移除黑名单
    *   Path： /users/blacklist/:uid
        Method： DELETE
    *路径参数：uid= 黑名单的用户id
    *
    * */
    @DeleteMapping("/blacklist/{uid}")
    public ResponseEntity delBlackList(@PathVariable("uid") Long blackUserId){
        //1.调用service
        usersService.delBlackList(blackUserId);
        //2.构造返回
        return ResponseEntity.ok(null);

    }


    /**
     * 修改手机号- 1 发送短信验证码
     * POST /users/phone/sendVerificationCode
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendVerificationCode() {
        //1. 获取手机号
        User user = UserHolder.getUser();
        String phone = user.getMobile();
        //2. 生成验证码发送
//        String code = RandomUtil.randomNumbers(6); //TODO  等到生产环境放开
        String code = "123456";
//        smsTemplate.sendSms(phone, code); //TODO  等到生产环境放开

        //3. 存储
        redisTemplate.opsForValue().set("SENDCODE:" + phone, code, 5, TimeUnit.MINUTES);
        return ResponseEntity.ok(null);
    }

    /**
     * 修改手机号 - 2 校验验证码
     * POST /users/phone/checkVerificationCode
     * 参数       verificationCode 验证码
     * 返回       verification 是否通过
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCode(@RequestBody Map map) {
        //1. 获取参数
        String code = map.get("verificationCode").toString();//验证码
        String phone = UserHolder.getUser().getMobile();

        //2. 调用方法比较
        Map restMap = usersService.checkVerificationCode(phone,code);

        //3. 返回
        return ResponseEntity.ok(restMap);
    }

    /**
     * 修改手机号 - 3 保存
     * POST /users/phone
     * 参数       phone 新手机号
     */
    @PostMapping("/phone")
    public ResponseEntity phone(@RequestBody Map map) {
        //1. 获取参数
        String phone = map.get("phone").toString();//手机号
        User user = UserHolder.getUser();
        user.setMobile(phone);

        //2. 调用方法比较
        usersService.update(user);

        //3. 返回
        return ResponseEntity.ok(null);
    }


    //以下是喜欢和取消喜欢
    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * GET /users/friends/:type
     * 路径参数：type	1 互相关注 2 我关注  3 粉丝 4 谁看过我
     * Query：page 当前页数     pagesize	页尺寸     nickname	昵称
     * 返回: 分页UserLikeListVo
     */
    @GetMapping("/friends/{type}")
    public ResponseEntity findFriends(@PathVariable("type")Integer type,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "5") Integer pagesize
    ){
        //判断用户要干什么
        PageResult pageResult = null;
        if (type == 1) {
            //互相喜欢
            pageResult = usersService.eachLove(type, page, pagesize);
        } else if (type == 2) {
            //喜欢
            pageResult = usersService.loveCount(type, page, pagesize);
        }else if (type == 3) {
            //粉丝
            pageResult = usersService.fanCount(type, page, pagesize);
        }else if (type == 4) {
            //谁看过我
            pageResult = usersService.findFriends(type, page, pagesize);

        }

        return ResponseEntity.ok(pageResult);
    }


    /*
     * 互相喜欢，喜欢，粉丝 - 统计
     * 接口路径：GET  /users/counts
     *请求参数：无
     * 返回值：
     * eachLoveCount，loveCount，fanCount
     * */
    @GetMapping("/counts")
    public ResponseEntity counts() {
        //获取用户id
        Long id = UserHolder.getUserId();
        //调用service
        Map map = usersService.counts(id);
        return ResponseEntity.ok(map);
    }


    /*
     * 粉丝喜欢
     * 接口路径：POST  /fans/{uid}
     * 请求参数：uid
     * 返回值：空
     * */
    @PostMapping("/fans/{uid}")
    public ResponseEntity fans(@PathVariable("uid") Long uid) {
        usersService.saveFans(uid);
        return ResponseEntity.ok(null);
    }

    /*
     * 喜欢取消
     * 接口路径：DELETE   /users/like/{uid}
     * 请求参数：uid，用户id
     * 返回值：null
     * */

    @DeleteMapping("/like/{uid}")
    public ResponseEntity notLike(@PathVariable("uid") Long uid) {
        usersService.notLike(uid);
        return ResponseEntity.ok(null);
    }

    /**
     * 是否喜欢（新增接口）
     * GET /users/:uid/alreadyLove
     */
    @GetMapping("/{uid}/alreadyLove")
    public ResponseEntity alreadyLove(@PathVariable("uid") Long uid) {
        boolean b = usersService.alreadyLove(uid);
        return ResponseEntity.ok(b);
    }

}
